package com.launch.carmanager.common.utils;

import android.text.TextUtils;
import android.util.Base64;

import com.blankj.utilcode.util.EncodeUtils;
import com.launch.carmanager.common.Constants;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by ganquan on 2019/3/28 10:47
 */
public class SignUtil {
    public static String key = Constants.PARTNER_KEY;
    public static String input_charset = "utf-8";
    private static final String ALGORITHM = "RSA";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 签名字符串
     *
     * @param text 需要签名的字符串
     * @return 签名结果
     */
    public static String sign(String text, String partner) {
        text = text + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    /**
     * 签名字符串
     *
     * @param text 需要签名的字符串
     * @return 签名结果
     */
    public static String verify(String text, String partner) {
//	    	fragment_main_layout = fragment_main_layout + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    public static String signPay(String content, String privateKey) {
        try {
//            BaSe64.decode(privateKey)
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    EncodeUtils.base64Decode(privateKey)
            );
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));

            byte[] signed = signature.sign();

//            return BaSe64.encode(signed);
            return EncodeUtils.base64Encode2String(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 数据加密处理
     */
    public static String dataDealWith(String data) {
        StringBuilder sb = new StringBuilder();
        sb.append("partner=" + Constants.PARTNER)
                .append("&appkey=" + Constants.PARTNER_KEY);
        if (!TextUtils.isEmpty(data))
            sb.append("&data=" + data);
        return SignUtil.verify(sb.toString(), Constants.PARTNER);
    }

    //Base64加密
    public static String getEncoder(byte[] str) throws UnsupportedEncodingException {
        return Base64.encodeToString(str, Base64.DEFAULT);
    }

    //Base64解密
    public static String getDecoder(String encode) throws UnsupportedEncodingException {
        byte[] asBytes = Base64.decode(encode, Base64.DEFAULT);
        return new String(asBytes, "utf-8");
    }

    /**
     * 获取 hmacSha1
     *
     * @param base
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static String hmacSha1(String base, String key) throws NoSuchAlgorithmException, InvalidKeyException {
        if (TextUtils.isEmpty(base) || TextUtils.isEmpty(key)) {
            return "";
        }
        String type = "test-HmacSHA1";
        SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
        Mac mac = Mac.getInstance(type);
        mac.init(secret);
        byte[] digest = mac.doFinal(base.getBytes());

        return Base64.encodeToString(digest, Base64.DEFAULT);

    }

    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";

    /**
     * 使用 HMAC-SHA1 签名方法对对encryptText进行签名
     *
     * @param encryptText 被签名的字符串
     * @param encryptKey  密钥
     * @return 返回被加密后的字符串
     * @throws Exception
     */
    public static byte[] HmacSHA1Encrypt(String encryptText,
                                         String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);
        byte[] text = encryptText.getBytes(ENCODING);
        // 完成 Mac 操作
        byte[] digest = mac.doFinal(text);
//        StringBuilder sBuilder = bytesToHexString( digest );
        return digest;
    }

    /**
     * 转换成Hex
     *
     * @param bytesArray
     */
    public static StringBuilder bytesToHexString(byte[] bytesArray) {
        if (bytesArray == null) {
            return null;
        }
        StringBuilder sBuilder = new StringBuilder();
        for (byte b : bytesArray) {
            String hv = String.format("%02x", b);
            sBuilder.append(hv);
        }
        return sBuilder;
    }

}
